package com.lzyjkz.quick_components.security.handle;

import cn.hutool.json.JSONUtil;
import com.lzyjkz.quick_components.entity.Response;
import com.lzyjkz.quick_components.exceptions.LoginExpiredException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        System.out.println("response.getStatus() = " + response.getStatus());
        if (authException instanceof LoginExpiredException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJsonStr(Response.fail(401, "登录过期，请重新登录")));
        }
    }
}
